const mongoose = require('mongoose');
const Router = require('koa-router');
const UserRouter = new Router();
const UserSchema = mongoose.model('User');

function setCookies(millisecond) {
  return {
    path: '/',
    maxAge: millisecond,
    httpOnly: false,
    overwrite: false,
  }
}
UserRouter.post('/login', async(ctx) => {
  try {
    const { userName, password } = ctx.request.body;
    const user = await UserSchema.findOne({userName}).exec();
    if (user) {
      if (user.password === password) {
        // 设置cookie
        ctx.cookies.set('userName', user.userName, setCookies(10 * 60 * 1000));
        ctx.body = {
          code: 200,
          message: '登录成功'
        }
      } else {
        ctx.body = {
          code: 400,
          message: '密码不正确'
        }
      }
    } else {
      ctx.body = {
        code: 400,
        message: '用户不存在'
      }
    }
    
  } catch (error) {
    ctx.body = {
      code: 500,
      message: error
    }
  }
})

// loginOut
UserRouter.get('/loginOut', async(ctx) => {
  // 退出登录
  // maxAge 的数值从浏览器的内存中删除cookie
  // maxAge 数值设为-1，还会存在浏览器的内存中,只是关闭浏览器时会清除
  try {
    ctx.cookies.set('userName', null, setCookies(0))
    ctx.body = {
      code: 200,
      message: '退出成功'
    }
  } catch (error) {
    ctx.body = {
      code: 500,
      message: error
    }
  }

})

module.exports = UserRouter;